package ele_handler

import (
	"fmt"
	"go-yuque/logger"
	"golang.org/x/net/html"
	"regexp"
	"strconv"
	"strings"
)

func init() {
	registerInitFunc(
		func() YuqueElementHandler {
			h := &hStruct{}
			return h
		})
}

// 段落处理器
type hStruct struct {
	BaseHandler
}

func (h *hStruct) checkNode(node *html.Node) bool {
	if node == nil || node.Type == html.TextNode || len(node.Data) <= 0 {
		return false
	}

	// 段落标签 h 开头，后面跟数字
	fst := node.Data[0]
	if fst != 'h' {
		return false
	}
	matched, _ := regexp.Match("^h[0-9]+$", []byte(node.Data))

	return matched
}

func (h *hStruct) preHandle() error { // 通过正则提取出标签中的数字
	reg := regexp.MustCompile(`\d+`)
	submatch := reg.FindStringSubmatch(h.node.Data)

	if len(submatch) > 0 {
		// 字符串转数字
		titleIdx, err := strconv.ParseInt(submatch[0], 10, 64)
		if err != nil {
			logger.Errorf("h标签,字符串转数字失败:%s", submatch[0])
			return err
		}
		h.WriteTextContext(fmt.Sprintf("%s ", strings.Repeat("#", int(titleIdx))))
	}

	return nil
}

func (h *hStruct) postHandle() error {
	h.WriteTextContext("\n")
	return nil
}
